<?php


namespace App\Lib\auth;

use App\Models\lin\LinGroup;
use App\Models\lin\LinGroupPermission;
use App\Models\lin\LinPermission;
use App\Models\lin\LinUserGroup;
use App\Services\token\LoginToken;

class AuthMap
{
    /**
     * 查询所有可分配的权限
     */
    public function getAuthList()
    {
        $auths = [];
        $routes = app()->routes->getRoutes();
        foreach ($routes as $value) {
            $route = $value->getAction();
            if (!empty($route['auth']) && !in_array('hidden', $route['auth'])) {
                $module = [
                    'name' => $route['auth'][0],
                    'module' => $route['auth'][1],
                ];
                $auths[] = $module;
                LinPermission::firstOrCreate($module);
            }
        }
        $permissions = LinPermission::all();
        foreach ($permissions as $permission) {
            if (!in_array($permission->makeHidden(['id', 'mount'])->toArray(), $auths)) {
                if ($permission->delete()) {
                    LinGroupPermission::wherePermissionId($permission->id)->delete();
                }
            }
        }
        return $permissions->where('mount', 1)->makeVisible(['id', 'mount'])->groupBy('module');
    }

    /**
     * 检查用户权限
     */
    public function checkUserAuth($actions)
    {
        $loginTokenService = LoginToken::getInstance();
        $uid = $loginTokenService->getCurrentUid();
        $groups = LinUserGroup::whereUserId($uid)->get();
        foreach ($groups as $group) {
            if ($group['group_id'] === 1) {
                return true;
            }
            $groupAuth = LinGroup::with('permissions')->find($group['group_id']);
            foreach ($groupAuth['permissions'] as $value) {
                if ($value['name'] === $actions[0]) {
                    return true;
                }
            }
        }
        return false;
    }
}
